package com.yishe.config.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * create by: chusifeng
 * Create in 2021/4/16 14:33
 * Description:用于访问Http的工具类对象
 * <p>Example</p>
 */
@Slf4j
@Component
@Configuration
@ConditionalOnClass(ProxyConfig.class)
public class HttpRestTemplateConfig {

    @Resource
    private ProxyConfig proxyConfig;


    /**
     * create by: chusifeng
     * Create in 2020/12/25 10:19
     * Descripton:自定义一个restTemplate并注册到spring容器中， 实现代理和https请求，
     * <p>Example</p>
     */
    @Bean(name = "restProxyTemplate")
    public RestTemplate restProxy(){
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());
        return new RestTemplate(httpRequestFactory);
    }
    /**
     * CYQ:使用
     * @return
     */
    private CloseableHttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        connectionManager.setMaxTotal(proxyConfig.getMaxTotal());
        connectionManager.setDefaultMaxPerRoute(proxyConfig.getMaxPerRoute());//服务并行接收的请求数量(注意)
        connectionManager.setValidateAfterInactivity(proxyConfig.getValidateAfterInactivity());


        //代理服务器
        HttpHost proxy = null;
        if (proxyConfig.getEnabled()){
            log.info("当前使用主机{}代理配置.",proxyConfig.getHost());
            proxy = new HttpHost(proxyConfig.getHost(), proxyConfig.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
        }else{
            log.info("当前使用无代理配置（开发环境），enabled=",proxyConfig.getEnabled());
        }

        //注册
        RequestConfig requestConfig = RequestConfig.custom()
            // 服务器返回数据(response)的时间，超时抛出read timeout
                .setSocketTimeout(proxyConfig.getReadTimeout())
            // 连接上服务器(握手成功)的时间，超时抛出connect timeout
                .setConnectTimeout(proxyConfig.getConnectTimeout())
            // 从连接池中获取连接的超时时间，超时抛出ConnectionPoolTimeoutException
                .setConnectionRequestTimeout(proxyConfig.getRequestTimeout())
                .setProxy(proxy)
                .build();
        return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build();
    }
}
